<template>
  <div>
    <!-- 我是宿舍集体考核 -->
    <!-- 表单查询 -->
    <div class="top">
      <TabList @onTabsValue="onTabsValue" />
      <Form
        ref="formRef"
        name="advanced_search"
        class="ant-advanced-search-form"
        :model="formState"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <Row :gutter="[16, 1]">
          <Col :span="6">
            <Form.Item label="宿舍楼" name="dormitoryId">
              <a-select
                ref="select"
                v-model:value="formState.dormitoryId"
                placeholder="请选择"
                allow-clear
                :get-popup-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                @change="onSelectDormitory"
              >
                <a-select-option
                  v-for="(item, index) of optionList.dormitoryList"
                  :key="index"
                  :value="item.id"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
            </Form.Item>
          </Col>
          <Col :span="6">
            <Form.Item label="房间名" name="roomId">
              <!-- <a-select ref="select" v-model:value="formState.roomId" @change="onFinish">
                <a-select-option value="">全部</a-select-option>
              </a-select> -->
              <a-cascader
                v-model:value="formState.roomId"
                allow-clear
                :options="optionList.roomList"
                placeholder="请选择"
                :load-data="onLoadDataRoom"
                :field-names="{ label: 'name', value: 'id' }"
                :get-popup-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                @change="onChangeRoomOne"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item v-if="activeKey !== 'all'" label="检查时间">
              <a-range-picker
                v-model:value="formState.createValue"
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始日期', '结束日期']"
                :get-calendar-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                :allow-clear="true"
                @change="onRangeChange"
                @ok="onRangeOk"
              />
            </Form.Item>
            <Form.Item v-else label="统计周期">
              <a-range-picker
                v-model:value="formState.createValue"
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始日期', '结束日期']"
                :get-calendar-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                :allow-clear="false"
                @change="onRangeChange"
                @ok="onRangeOk"
              />
            </Form.Item>
          </Col>
        </Row>
        <div class="search">
          <div class="search-btn">
            <a-button type="primary" html-type="submit" @click="onSearch(1)">查询</a-button>
            <a-button ghost style="margin: 0 0 0 16px" @click="resetForm">重置</a-button>
          </div>
        </div>
      </Form>
    </div>
    <!-- 列表 -->
    <div class="below">
      <div v-if="activeKey === 'all' && rankingState" class="ranking">
        <span class="ranking-text">排名</span>
        <CloseOutlined style="font-size: 20px; color: #c2c2c2; cursor: pointer" @click="close" />
      </div>
      <div class="search">
        <div>
          <div v-if="stateUser.identity === 8">
            <a-button
              v-if="activeKey !== 'all'"
              :type="delStateClick"
              :disabled="!delState"
              :loading="btnLoading"
              @click="onDelete"
              >删除</a-button
            >
          </div>
        </div>
        <div class="search-btn-right">
          <a-button
            v-if="activeKey === 'all' && rankingState && rankingOrder"
            type="primary"
            style="margin-right: 16px; display: flex; align-items: center"
            html-type="submit"
            ghost
            @click="asc"
          >
            <template #icon><SwapOutlined :style="{ transform: 'rotateZ(90deg)' }" /></template>
            正序
          </a-button>
          <a-button
            v-if="activeKey === 'all' && rankingState && !rankingOrder"
            type="primary"
            style="margin-right: 16px; display: flex; align-items: center"
            html-type="submit"
            ghost
            @click="desc"
          >
            <template #icon><SwapOutlined :style="{ transform: 'rotateZ(90deg)' }" /></template>
            反序
          </a-button>
          <a-button
            v-if="activeKey === 'all' && !rankingState"
            type="primary"
            style="margin-right: 16px; display: flex; align-items: center"
            html-type="submit"
            ghost
            @click="LookRanking()"
          >
            <template #icon><ToTopOutlined /></template>
            查看排行
          </a-button>
          <a-button
            :type="leadingOut"
            :ghost="isStudentLeadingOut"
            :loading="btnLoading"
            style="display: flex; align-items: center"
            @click="onExport"
          >
            <template #icon><ToTopOutlined /></template>
            导出
          </a-button>
        </div>
      </div>
      <!-- 表格 -->
      <div>
        <a-table
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :data-source="tableData.records"
          :row-key="record => (activeKey === 'all' ? record.roomId : record.id)"
          :pagination="false"
          :loading="loading"
          :scroll="{ x: 1300 }"
        >
          <!-- <template v-slot:emptyText>{{ loading ? '' : '暂无数据' }}</template> -->
          <template v-slot:emptyText>
            <div class="zz-global-nodata">
              <img
                v-if="searchStatus * 1 === 0"
                src="@/assets/images/accommodation/default-no-data.png"
                alt=""
              />
              <img v-else src="@/assets/images/accommodation/no-data-search-new.png" alt="" />
            </div>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'itemNames'">
              <div
                style="
                  font-size: 14px;
                  color: #222222;
                  width: 170px;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
              >
                <Tooltip
                  :overlay-style="{ whiteSpace: 'normal' }"
                  :get-popup-container="
                    triggerNode => {
                      return triggerNode.parentNode;
                    }
                  "
                  placement="topLeft"
                  :title="record.itemNames"
                >
                  {{ record.itemNames }}
                </Tooltip>
              </div>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button
                type="primary"
                size="small"
                ghost
                @click="
                  onDeta(
                    record.id,
                    record.studentUserId,
                    record.dormitoryName,
                    record.roomName,
                    record.roomId
                  )
                "
                >查看</a-button
              >
            </template>
          </template>
        </a-table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <span style="color: #999999; margin-right: 8px">共{{ tableData.pages }}页</span>
        <a-pagination
          v-model:current="tableData.current"
          v-model:pageSize="tableData.size"
          :page-size-options="pageSizeOptions"
          show-quick-jumper
          :total="tableData.total"
          :show-size-changer="true"
          @change="onChangePagination"
        />
      </div>
    </div>
  </div>

  <DelDialog v-if="delDialogState" @on-cancel-del="onCancelDel" @onOk="onOk" />
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { Form, Row, Col, Message, Cascader, Tooltip, message } from 'ant-design-vue';
import { ToTopOutlined, CloseOutlined, SwapOutlined } from '@ant-design/icons-vue';
import DelDialog from '../components/delDialog/index.vue';
import TabList from '../components/tebPane/TabPane.vue';
import {
  dormitoryCheckList,
  dormitoryComplex,
  delDetails,
  dormitoryCheckRanking,
  exportDormitoryExamine,
  exportDormitoryComplex,
  exportdormitoryCheckRanking,
  dormitoryDetails
} from '@/api/assessment/dormitoryCollective';
import { getDormitory, floorList, floorRoom, roomBedNum } from '@/api/common';
import dayjs from 'dayjs';
import moment from 'moment';
import { useStore } from 'vuex';
import { debounce } from '@/utils/debounce.js';
const dayCreateValue = ref([]);
const formState = ref({
  itemSuperiorId: 0, // 考核分类，0为综合查询 其余分类依照学校设置为准
  studentName: '', // 姓名
  releaseUserName: '',
  gradeId: '', // 年级
  classId: '', // 班级
  dormitoryId: undefined, // 宿舍楼
  sex: '', // 性别
  roomId: [], // 房间名称
  studentState: '', // 学生状态
  allocationStatus: '', // 分配状态
  startTime: '', // 开始时间
  endTime: '', // 结束时间
  createValue: dayCreateValue.value,
  current: 1,
  size: 10
});
const router = useRouter();
// tabs 激活标签
const activeKey = ref('');
const searchStatus = ref(0);
const roomId = ref('');
onMounted(() => {
  let dormitoryCollectiveQuery = localStorage.getItem('dormitoryCollectiveQuery');
  if (
    !dormitoryCollectiveQuery ||
    dormitoryCollectiveQuery === null ||
    dormitoryCollectiveQuery === undefined
  ) {
    console.log('走进来了吗。。。。');
    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
  }

  let DCpageNum = sessionStorage.getItem('DCpageNum');
  let DCtabsNum = JSON.stringify(sessionStorage.getItem('DCtabsNum'));
  tableData.value.current = Number(DCpageNum);
  console.log(typeof DCtabsNum);
  activeKey.value = DCtabsNum;
  // onTabsValue(DCtabsNum);
  // sessionStorage.removeItem('DCpageNum');
  // sessionStorage.removeItem('DCtabsNum');
  console.log(DCpageNum, 'DCpageNum');
  console.log(DCtabsNum, 'DCtabsNum');
  dataForm();

  obtainQuery();
});
function obtainQuery() {
  let dormitoryCollectiveQuery = localStorage.getItem('dormitoryCollectiveQuery');
  console.log('我cnim宿舍集体考核', dormitoryCollectiveQuery);
  if (dormitoryCollectiveQuery && dormitoryCollectiveQuery !== null) {
    let dormitoryCollectiveQueryJson = JSON.parse(dormitoryCollectiveQuery);
    optionList.value = dormitoryCollectiveQueryJson.optionList;
    activeKey.value = dormitoryCollectiveQueryJson.activeKey;
    formState.value = dormitoryCollectiveQueryJson.formState;

    if (
      !dormitoryCollectiveQuery ||
      dormitoryCollectiveQuery === null ||
      dormitoryCollectiveQuery === undefined
    ) {
      dayCreateValue.value = [
        dayjs(moment().format('YYYY-MM-DD 00:00')),
        dayjs(moment().format('YYYY-MM-DD 23:59'))
      ];
      formState.value.createValue = dayCreateValue.value;
    } else {
      if (formState.value.startTime && formState.value.startTime !== null) {
        dayCreateValue.value = [
          dayjs(moment().format(formState.value.startTime)),
          dayjs(moment().format(formState.value.endTime))
        ];
      } else {
        dayCreateValue.value = [];
      }

      formState.value.createValue = dayCreateValue.value;
      console.log('wcndlgd', formState.value.createValue);
    }
    console.log('ojbk----', formState.value);
    console.log('dormitoryCollectiveQueryJson', dormitoryCollectiveQueryJson);
    console.log('activeKey.value', activeKey.value);
    onSearch();

    if (
      formState.value.dormitoryId &&
      formState.value.dormitoryId !== null &&
      optionList.value.roomList.length === 0
    ) {
      getFloorList(formState.value.dormitoryId);
    }
  } else {
    getRoomBedNum();
    getDormitoryList();
  }
}
const loading = ref(true);
const store = useStore();
const stateUser = computed(() => store.state.user.STATE_USER);
// const stateUser = ref(JSON.parse(localStorage.getItem('STATE_USER')));

// 下拉选项列表
const optionList = ref({
  dormitoryList: [],
  roomList: [],
  roomBedNum: []
});
// 获取宿舍楼列表
const getRoomBedNum = () => {
  roomBedNum().then(res => {
    if (res.data.code === 200) {
      optionList.value.roomBedNum = res.data.data;
    }
  });
};
// 获取宿舍楼列表
const getDormitoryList = () => {
  getDormitory(0).then(res => {
    if (res.data.code === 200) {
      optionList.value.dormitoryList = res.data.data;
      optionList.value.roomList = res.data.data;
      optionList.value.roomList.forEach(elem => {
        elem.isLeaf = false;
      });
    }
  });
};
// 获取宿舍楼层列表
const getFloorList = value => {
  floorList(value).then(res => {
    if (res.data.code === 200) {
      res.data.data.forEach(elem => {
        let obj = {
          name: `${elem.storey}楼`,
          storey: elem.storey,
          id: elem.storey,
          dormitoryId: elem.id,
          floor: elem.floor,
          isLeaf: false
        };
        optionList.value.roomList.push(obj);
      });
    }
  });
};
// 改变宿舍楼回调
const onSelectDormitory = value => {
  formState.value.roomId = [];
  optionList.value.roomList = [];
  if (value !== undefined) {
    getFloorList(value);
  } else {
    getDormitoryList();
  }
};
// 选择房间回调
const onChangeRoomOne = (value, selectedOptionsOne) => {
  // if (selectedOptionsOne[0].dormitoryId !== undefined) {
  //   formState.value.dormitoryId = selectedOptionsOne[0].dormitoryId;
  // } else {
  //   formState.value.dormitoryId = value[0];
  // }
  // if (value.length === 3) {
  //   formState.value.dormitoryId = value[0];
  // }

  if (value !== undefined) {
    if (value.length === 3) {
      formState.value.dormitoryId = value[0];
    }
  } else {
    formState.value.roomId = undefined;
  }
};
// 选择房间异步动态加载
const onLoadDataRoom = selectedOptionsOne => {
  if (!formState.value.dormitoryId) {
    formState.value.dormitoryId = selectedOptionsOne[0].id;
  }

  const targetOption = selectedOptionsOne[selectedOptionsOne.length - 1];
  targetOption.loading = true; // load options lazily
  if (targetOption.dormitoryName) {
    floorList(targetOption.id).then(res => {
      if (res.data.code === 200) {
        targetOption.loading = false;
        targetOption.children = [];
        res.data.data.forEach(elem => {
          let obj = {
            name: `${elem.storey}楼`,
            id: elem.storey,
            storey: elem.storey,
            floor: elem.floor,
            isLeaf: false
          };
          targetOption.children.push(obj);
        });
        optionList.value.roomList = [...optionList.value.roomList];
      }
    });
  }
  if (targetOption.floor) {
    let id = selectedOptionsOne[0].floor ? formState.value.dormitoryId : selectedOptionsOne[0].id;
    floorRoom(id, targetOption.storey).then(res => {
      if (res.data.code === 200) {
        targetOption.loading = false;
        targetOption.children = [];
        res.data.data.forEach(elem => {
          let obj = {
            name: elem.name,
            id: elem.id,
            isLeaf: true
          };
          targetOption.children.push(obj);
        });
        optionList.value.roomList = [...optionList.value.roomList];
      }
    });
  }
};

// 表格信息
const tableData = ref([]);
const records = ref([]);
// 获取表格信息
function getTabsList(parmas) {
  loading.value = true;
  tableData.value.records = [];
  dormitoryCheckList(parmas).then(res => {
    if (res.data.code === 200) {
      tableData.value = res.data.data;
      loading.value = false;
      records.value = res.data.data.records;
      if (records.value.length > 0) {
        roomId.value = records.value.map(item => {
          return item.roomId;
        });
      } else {
        roomId.value = '';
      }
      //   roomId.value = records.value.map(item => {
      //     return item.roomId;
      //   });
    }
  });
}
// 获取表格信息--综合查询
function getTabsListComplex(parmas) {
  loading.value = true;
  tableData.value.records = [];
  dormitoryComplex(parmas).then(res => {
    if (res.data.code === 200) {
      tableData.value = res.data.data;
      loading.value = false;
    }
  });
}
const btnLoading = ref(false);
// 导出
const onExport = debounce(function () {
  let roomId;
  btnLoading.value = true;
  if (
    formState.value.roomId &&
    formState.value.roomId !== undefined &&
    formState.value.roomId !== null
  ) {
    roomId = formState.value.roomId[1];
  } else {
    roomId = '';
  }
  if (activeKey.value === 'all' && rankingState.value === true) {
    if (selectedRows.value.length <= 0) {
      btnLoading.value = false;
      Message.warning('请至少选择一条导出的数据');
    } else {
      let objRank = {
        startTime: formState.value.startTime, // 检查时间开始
        endTime: formState.value.endTime, // 检查时间结束
        scoreRankAsc: !rankingOrder.value, // 排序
        roomIds: []
      };
      selectedRows.value.forEach(item => {
        objRank.roomIds.push(item.roomId);
      });
      exportdormitoryCheckRanking(objRank).then(res => {
        let url = window.URL.createObjectURL(res.data);
        let file = document.createElement('a');
        document.body.appendChild(file);
        file.href = url;
        file.download = '集体综合考核排名.xls';
        file.click();
        btnLoading.value = false;
        window.URL.revokeObjectURL(url);
      });
    }
  } else if (activeKey.value === 'all') {
    if (selectedRows.value.length <= 0) {
      btnLoading.value = false;
      Message.warning('请至少选择一条导出的数据');
    } else {
      let obj = {
        dormitoryId: formState.value.dormitoryId, // 宿舍楼
        // roomId: formState.value.roomId.length ? formState.value.roomId[1] : '', // 房间名称
        roomId: roomId,
        startTime: formState.value.startTime, // 检查时间开始
        endTime: formState.value.endTime, // 检查时间结束
        roomIds: []
      };
      selectedRows.value.forEach(item => {
        obj.roomIds.push(item.roomId);
      });
      exportDormitoryComplex(obj).then(res => {
        let url = window.URL.createObjectURL(res.data);
        let file = document.createElement('a');
        document.body.appendChild(file);
        file.href = url;
        file.download = '集体综合考核.xls';
        file.click();
        btnLoading.value = false;
        window.URL.revokeObjectURL(url);
      });
    }
  } else {
    if (selectedRows.value.length <= 0) {
      btnLoading.value = false;
      Message.warning('请至少选择一条导出的数据');
    } else {
      // roomId.value = [];
      // selectedRows.value.forEach(i => {
      //   roomId.value.push(i.id);
      // });
      // console.log(selectedRows.value, 'selectedRows.value');
      // let obj = {
      //   itemSuperiorId: formState.value.itemSuperiorId,
      //   ids: roomId.value
      // };
      // console.log(roomId.value, 'roomId.valueroomId.value');
      // exportDormitoryExamine(obj).then(res => {
      //   let url = window.URL.createObjectURL(res.data);
      //   let file = document.createElement('a');
      //   document.body.appendChild(file);
      //   file.href = url;
      //   file.download = '集体考核.xls';
      //   file.click();
      //   window.URL.revokeObjectURL(url);
      // });
      let roomIdNew = [];
      selectedRows.value.forEach(i => {
        roomIdNew.push(i.id);
      });
      console.log(selectedRows.value, 'selectedRows.value');
      let obj = {
        itemSuperiorId: formState.value.itemSuperiorId,
        ids: roomIdNew
      };
      console.log(roomIdNew, 'roomId.valueroomId.value');
      exportDormitoryExamine(obj).then(res => {
        let url = window.URL.createObjectURL(res.data);
        let file = document.createElement('a');
        document.body.appendChild(file);
        file.href = url;
        file.download = '集体考核.xls';
        file.click();
        btnLoading.value = false;
        window.URL.revokeObjectURL(url);
      });
    }
  }
}, 500);
// tabs改变回调dormitoryName
function onTabsValue(e, status) {
  console.log('eee-------------------', e);
  console.log('status', status);
  searchStatus.value = 0;
  let dormitoryCollectiveQuery = localStorage.getItem('dormitoryCollectiveQuery');
  if (status * 1 === 1) {
    localStorage.removeItem('dormitoryCollectiveQuery');
    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
    formState.value.startTime = dayCreateValue.value[0];
    formState.value.endTime = dayCreateValue.value[1];
    resetForm(e);
  }

  if (
    !dormitoryCollectiveQuery ||
    dormitoryCollectiveQuery === null ||
    dormitoryCollectiveQuery === undefined
  ) {
    // formState.value.startTime = '';
    // formState.value.endTime = '';
    activeKey.value = e.id;

    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
    formState.value.startTime = dayCreateValue.value[0];
    formState.value.endTime = dayCreateValue.value[1];
  } else {
    activeKey.value = JSON.parse(dormitoryCollectiveQuery).activeKey;
  }
  loading.value = true;
  formState.value.createValue = dayCreateValue.value;

  selectedRows.value = [];
  selectedRowKeys.value = [];

  if (e.id !== undefined) {
    onFinish(e.id);
    if (
      !dormitoryCollectiveQuery ||
      dormitoryCollectiveQuery === null ||
      dormitoryCollectiveQuery === undefined
    ) {
      activeKey.value = e.id;
    }

    rankingState.value = false;
  } else {
    onFinish('all');
    activeKey.value = 'all';
    rankingState.value = false;
  }
  console.log('value00', formState.value);
  dataForm();
  if (
    !dormitoryCollectiveQuery ||
    dormitoryCollectiveQuery === null ||
    dormitoryCollectiveQuery === undefined
  ) {
    resetForm();
  }
}

// 重置
const resetForm = e => {
  searchStatus.value = 0;
  console.log('eeeeeeeeeeeeeeeeeee', e);
  formState.value.createValue = dayCreateValue.value;
  formState.value.startTime = startTime;
  formState.value.endTime = endTime;
  if (e !== null && e) {
    if (e.id && e.id !== undefined && e.id !== null) {
      if (e.id !== 'all') {
        formState.value.itemSuperiorId = e.id;
      } else {
        formState.value.itemSuperiorId = 0;
      }
    }
  }

  dayCreateValue.value = [
    dayjs(moment().format(formState.value.startTime)),
    dayjs(moment().format(formState.value.endTime))
  ];
  formState.value.size = 10;
  formState.value.createValue = dayCreateValue.value;
  // formRef.value.resetFields();
  formState.value.dormitoryId = undefined;
  formState.value.roomId = [];
  onSearch();
  getDormitoryList();
};

// 查询 按钮
const onSearch = status => {
  // 手动点击
  if (status * 1 === 1) {
    searchStatus.value = 1;
    formState.value.current = 1;
  }
  selectedRows.value = [];
  selectedRowKeys.value = [];
  if (activeKey.value === 'all' && rankingState.value === true) {
    orderby(!rankingOrder.value);
  } else {
    // formState.value.roomId.length
    //       ? formState.value.roomId[formState.value.roomId.length - 1]
    //       : null, // 房间名称

    let roomId;
    if (
      formState.value.roomId &&
      formState.value.roomId !== undefined &&
      formState.value.roomId !== null
    ) {
      roomId = formState.value.roomId[formState.value.roomId.length - 1];
    } else {
      roomId = undefined;
    }
    console.log('我是3', formState.value.itemSuperiorId);
    let obj = {
      data: {
        dormitoryId: formState.value.dormitoryId, // 宿舍楼
        roomId: roomId, // 房间名称
        startTime: formState.value.startTime, // 检查时间开始
        endTime: formState.value.endTime, // 检查时间结束
        roomIds: [],
        itemSuperiorId: formState.value.itemSuperiorId
      },
      current: formState.value.current,
      size: formState.value.size
    };
    // console.log(formState.value.itemSuperiorId, 'formState.value.itemSuperiorId');
    if (formState.value.itemSuperiorId !== 0) {
      getTabsList(obj);
    } else {
      getTabsListComplex(obj);
    }
  }
};
let delList = ref([]);

// 表格多选
const selectedRowKeys = ref([]);
const selectedRows = ref([]);
// table 多选回调
const onSelectChange = (rowKeys, rows) => {
  selectedRowKeys.value = rowKeys;
  delList.value = rowKeys;
  selectedRows.value = rows;
};

// 删除
const delState = ref(false);
const delStateClick = computed(() => {
  let str = '';
  if (delState.value) str = 'primary';
  return str;
});
watch(selectedRowKeys, value => {
  if (value.length) {
    delState.value = true;
  } else {
    delState.value = false;
  }
});

// 是否选择导出学生
const isStudentLeadingOut = ref(false);
const leadingOut = computed(() => {
  let str = '';
  if (isStudentLeadingOut.value) str = 'primary';
  return str;
});
watch(selectedRowKeys, value => {
  if (value.length) {
    isStudentLeadingOut.value = true;
  } else {
    isStudentLeadingOut.value = false;
  }
});
// 页码
// const current = ref(1);
// 指定每页条数
const pageSizeOptions = ref(['10', '20', '30', '40', '50', '100', '500', '1000']);
// 分页发生改变
const onChangePagination = value => {
  let roomId;
  if (
    formState.value.roomId &&
    formState.value.roomId !== undefined &&
    formState.value.roomId !== null
  ) {
    roomId = formState.value.roomId[formState.value.roomId.length - 1];
  } else {
    roomId = undefined;
  }
  let obj = {
    data: {
      dormitoryId: formState.value.dormitoryId, // 宿舍楼
      // roomId: formState.value.roomId.length
      //   ? formState.value.roomId[formState.value.roomId.length - 1]
      //   : null, // 房间名称
      roomId: roomId,
      startTime: formState.value.startTime, // 检查时间开始
      endTime: formState.value.endTime, // 检查时间结束
      roomIds: [],
      itemSuperiorId: formState.value.itemSuperiorId
    },
    current: tableData.value.current,
    size: tableData.value.size
  };
  formState.value.current = tableData.value.current;
  formState.value.size = tableData.value.size;
  // console.log(formState.value.itemSuperiorId, 'formState.value.itemSuperiorId');
  if (formState.value.itemSuperiorId !== 0) {
    getTabsList(obj);
  } else {
    // 综合检查
    console.log(order.value, 'order.value');
    if (activeKey.value === 'all' && !rankingState.value) {
      // 综合检查
      obj = {
        data: {
          dormitoryId: formState.value.dormitoryId, // 宿舍楼
          // roomId: formState.value.roomId.length
          //   ? formState.value.roomId[formState.value.roomId.length - 1]
          //   : null, // 房间名称
          roomId: roomId,
          startTime: formState.value.startTime, // 检查时间开始
          endTime: formState.value.endTime, // 检查时间结束
          roomIds: [],
          itemSuperiorId: formState.value.itemSuperiorId
        },
        current: tableData.value.current,
        size: tableData.value.size
      };
      // 综合检查接口
      getTabsListComplex(obj);
    } else {
      // 排序
      obj = {
        data: {
          dormitoryId: formState.value.dormitoryId, // 宿舍楼
          // roomId: formState.value.roomId.length
          //   ? formState.value.roomId[formState.value.roomId.length - 1]
          //   : null, // 房间名称
          roomId: roomId,
          startTime: formState.value.startTime, // 检查时间开始
          endTime: formState.value.endTime, // 检查时间结束
          roomIds: [],
          itemSuperiorId: formState.value.itemSuperiorId
        },
        current: tableData.value.current,
        size: tableData.value.size,
        orders: [
          {
            column: 'scoreRank',
            asc: order.value
          }
        ]
      };
      // 排序接口
      dormitoryCheckRanking(obj).then(res => {
        tableData.value = res.data.data;
      });
    }
  }
};

// 时间设置
let startTime = moment(new Date(new Date(new Date().toLocaleDateString()).getTime())).format(
  'YYYY-MM-DD HH:mm:ss'
);
let endTime = moment(
  new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
).format('YYYY-MM-DD HH:mm:ss');
// 查看详情
const onDeta = (id, studentUserId, dormitoryName, roomName, roomId) => {
  console.log('id是', id);
  saveQuery();
  console.log(formState.value.current, tableData.value.current, activeKey.value);
  sessionStorage.setItem('DCpageNum', tableData.value.current);
  sessionStorage.setItem('DCtabsNum', activeKey.value);
  let path = null;
  if (formState.value.startTime === '') {
    formState.value.startTime = startTime;
  }
  if (formState.value.endTime === '') {
    formState.value.endTime = endTime;
  }
  if (activeKey.value === 'all') {
    path = '/check/dormitoryCollective/allDeta';
    router.push({
      path,
      query: {
        examineId: id,
        dormitoryName: dormitoryName, // 宿舍楼
        roomName: roomName, // 房间名称
        roomId: roomId, // 房间id
        examineStartTime: formState.value.startTime, // 检查时间开始
        examineStopTime: formState.value.endTime // 检查时间结束
      }
    });
  } else {
    let obj = {
      examineId: id.toString()
    };
    dormitoryDetails(obj).then(res => {
      console.log(res.data.code);
      if (res.data.code === 200) {
        path = '/check/dormitoryCollective/disciplineDeta';
        router.push({
          path,
          query: {
            examineId: id
          }
        });
      } else {
        message.error(res.data.msg);
        // 在这要刷新列表
        onSearch();
      }
    });
  }
  // formState.value.endTime = '';
  // formState.value.startTime = '';
};
function saveQuery() {
  let json = {
    activeKey: activeKey.value,
    formState: formState.value,
    optionList: optionList.value
  };
  console.log('保存的时候宿舍集体考核', json);
  localStorage.setItem('dormitoryCollectiveQuery', JSON.stringify(json));
}
// 时间设置
const onRangeChange = (dates, dateString) => {
  formState.value.createValue = dates;
  console.log('dates', dates);
  if (dateString.length > 0) {
    formState.value.startTime = dateString[0];
    formState.value.endTime = dateString[1];
  }
};

const onRangeOk = value => {
  console.log('onOk: ', value);
};

const dataColumns = reactive([
  {
    key: 'dormitoryName',
    title: '宿舍楼',
    dataIndex: 'dormitoryName',
    scopedSlots: { customRender: 'dormitoryName' },
    fixed: 'left'
  },
  {
    key: 'roomName',
    title: '房间名',
    dataIndex: 'roomName',
    scopedSlots: { customRender: 'roomName' }
  },
  {
    key: 'totalMarkScore',
    title: '得/扣分',
    dataIndex: 'totalMarkScore',
    scopedSlots: { customRender: 'totalMarkScore' }
  }
]);
const dataActive = reactive({
  title: '操作',
  key: 'action',
  dataIndex: 'action',
  scopedSlots: { customRender: 'action' },
  fixed: 'right',
  width: 100
});

let columns = ref([]);
const dataForm = () => {
  if (activeKey.value === 'all' && rankingState.value === true) {
    columns.value = [
      {
        key: 'scoreRank',
        title: '排名',
        dataIndex: 'scoreRank',
        scopedSlots: { customRender: 'scoreRank' }
      },
      ...dataColumns,
      dataActive
    ];
  } else if (activeKey.value !== 'all') {
    columns.value = [
      ...dataColumns,
      {
        key: 'examineGrade',
        title: '评分等级',
        dataIndex: 'examineGrade',
        scopedSlots: { customRender: 'examineGrade' }
      },
      {
        key: 'itemNames',
        title: '扣分项',
        dataIndex: 'itemNames',
        scopedSlots: { customRender: 'itemNames' },
        width: 310
      },
      {
        key: 'examineTime',
        title: '检查时间',
        dataIndex: 'examineTime',
        scopedSlots: { customRender: 'examineTime' }
      },
      {
        key: 'createUserName',
        title: '检查人',
        dataIndex: 'createUserName',
        scopedSlots: { customRender: 'createUserName' }
      },
      dataActive
    ];
  } else {
    columns.value = [...dataColumns, dataActive];
  }
};
const dateFormat = 'YYYY-MM-DD hh:mm';
const timeRange = ref([
  moment(moment(new Date()).format('YYYY-MM-DD 00:00:00')),
  moment(moment(new Date()).format('YYYY-MM-DD 23:59:59'))
]);

// 表单查询
const formRef = ref();

// label样式
// const labelCol = reactive({
//   xs: { span: 4 },
//   sm: { span: 6 }
// });
// const wrapperCol = reactive({
//   xs: { span: 24 },
//   sm: { span: 16 }
// });
const labelCol = reactive({
  xs: { span: 8 },
  xl: { span: 8 },
  xxl: { span: 6 }
});
const wrapperCol = reactive({
  xs: { span: 24 },
  xl: { span: 24 },
  xxl: { span: 24 }
});
const onFinish = values => {
  let roomId;
  if (
    formState.value.roomId &&
    formState.value.roomId !== undefined &&
    formState.value.roomId !== null
  ) {
    roomId = formState.value.roomId[formState.value.roomId.length - 1];
  } else {
    roomId = undefined;
  }
  let dormitoryCollectiveQuery = localStorage.getItem('dormitoryCollectiveQuery');
  if (values === 'all') {
    values = 0;
  }
  console.log('ooo000', values);
  let parmas = {
    data: {
      itemSuperiorId: values,
      dormitoryId: formState.value.dormitoryId,
      // roomId: formState.value.roomId
      //   ? formState.value.roomId[formState.value.roomId.length - 1]
      //   : null, // 房间名称
      roomId: roomId,
      startTime: formState.value.startTime,
      endTime: formState.value.endTime
    },
    current: 1, // 当前页
    pages: 0, // 总页数
    size: 10, // 当前条数
    total: 0 // 总条数
  };
  if (
    !dormitoryCollectiveQuery ||
    dormitoryCollectiveQuery === null ||
    dormitoryCollectiveQuery === undefined
  ) {
    if (formState.value.startTime === '') {
      formState.value.startTime = startTime;
    }
    if (formState.value.endTime === '') {
      formState.value.endTime = endTime;
    }
    formState.value.itemSuperiorId = values;
    formState.value.current = parmas.current;
    formState.value.size = parmas.size;
    activeKey.value = values;
    if (values === 0) {
      activeKey.value = 'all';
    }
  }
  console.log('sjbwy', formState.value.itemSuperiorId);

  /* if (formState.value.itemSuperiorId !== 0) {
    getTabsList(parmas);
  } else {
    getTabsListComplex(parmas);
  } */
};

// const pageNum = ref(1);
// const pageSize = ref(10);
// const total = ref(500);

const rankingState = ref(false); // 排名

const rankingOrder = ref(true);
// 查看排行
function LookRanking() {
  tableData.value.current = 1;
  rankingState.value = true;
  orderby(0);
  dataForm();
}
// 正序
function asc() {
  rankingOrder.value = false;
  orderby(true);
}
// 反序
function desc() {
  rankingOrder.value = true;
  orderby(false);
}
let order = ref(true);
function orderby(orders) {
  let roomId;
  if (
    formState.value.roomId &&
    formState.value.roomId !== undefined &&
    formState.value.roomId !== null
  ) {
    roomId = formState.value.roomId[formState.value.roomId.length - 1];
  } else {
    roomId = undefined;
  }
  console.log(123, orders);
  order.value = orders;
  if (formState.value.examineStartTime === '') {
    formState.value.examineStartTime = startTime;
  }
  if (formState.value.examineStopTime === '') {
    formState.value.examineStopTime = endTime;
  }

  let obj = [];
  if (orders !== 0) {
    obj = {
      data: {
        dormitoryId: formState.value.dormitoryId, // 宿舍楼
        // roomId: formState.value.roomId.length
        //   ? formState.value.roomId[formState.value.roomId.length - 1]
        //   : null, // 房间名称
        roomId: roomId,
        startTime: formState.value.startTime, // 检查时间开始
        endTime: formState.value.endTime, // 检查时间结束
        roomIds: [],
        itemSuperiorId: formState.value.itemSuperiorId
      },
      current: tableData.value.current,
      size: tableData.value.size,
      orders: [
        {
          column: 'scoreRank',
          asc: orders
        }
      ]
    };
  } else {
    obj = {
      data: {
        dormitoryId: formState.value.dormitoryId, // 宿舍楼
        // roomId: formState.value.roomId.length
        //   ? formState.value.roomId[formState.value.roomId.length - 1]
        //   : null, // 房间名称
        roomId: roomId,
        startTime: formState.value.startTime, // 检查时间开始
        endTime: formState.value.endTime, // 检查时间结束
        roomIds: [],
        itemSuperiorId: formState.value.itemSuperiorId
      },
      current: tableData.value.current,
      size: tableData.value.size
    };
  }

  dormitoryCheckRanking(obj).then(res => {
    tableData.value = res.data.data;
  });
}

function close() {
  rankingState.value = false;
  dataForm();
  onFinish(activeKey.value);
  onSearch();
}

const delDialogState = ref(false); // 确认是否删除弹窗
const onCancelDel = () => {
  console.log(222);
  delDialogState.value = false;
  btnLoading.value = false;
};
const onDelete = debounce(function onDelete() {
  if (selectedRows.value.length <= 0) {
    Message.warning('请至少选择一条删除的数据');
  } else {
    delDialogState.value = true;
  }
}, 500);
const onOk = debounce(function () {
  btnLoading.value = true;
  delDetails(delList.value)
    .then(res => {
      if (res.data.code === 200) {
        formState.value.roomId = null;
        let obj = {
          data: formState.value,
          current: tableData.value.current,
          size: tableData.value.size
        };
        getTabsList(obj);
        btnLoading.value = false;
        delDialogState.value = false;
        Message.success('删除成功');
      }
    })
    .catch(() => {
      btnLoading.value = false;
      delDialogState.value = false;
    });
}, 500);
</script>

<style lang="less" scoped>
.top,
.below {
  width: 100%;
  padding: 24px 0;
  background: #ffffff;
  border-radius: 4px;
}
.below {
  padding: 24px;
  min-height: 710px;
  .ranking {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #e1dddd;
    padding-bottom: 16px;
    margin-bottom: 16px;
    &-text {
      font-size: 18px;
      font-family: Source Han Sans CN, Source Han Sans CN-Medium;
      font-weight: 500;
      color: #222222;
    }
  }
  .search {
    display: flex;
    justify-content: space-between;
    margin-bottom: 24px;
    .search-btn-right {
      width: 40%;
      display: flex;
      justify-content: flex-end;
    }
  }
  /deep/.micro-dormitory-empty-normal .micro-dormitory-empty-image {
    height: 100px;
  }
  /deep/.micro-dormitory-empty-img-simple {
    width: 100px;
    height: 80px;
  }
}
.top {
  margin-bottom: 24px;
  .search {
    display: flex;
    justify-content: flex-end;
    margin-right: 22px;
  }
}
.pagination {
  align-items: center;
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}
/deep/.micro-dormitory-tabs-tab {
  font-size: 16px;
  padding: 12px 24px;
}
/deep/.micro-dormitory-select-arrow {
  top: 40%;
}
/deep/.micro-dormitory-select-selection-item {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  width: 8rem !important;
}
// /deep/.micro-dormitory-cascader-menu {
//   white-space: nowrap !important;
//   overflow: hidden !important;
//   text-overflow: ellipsis !important;
//   width: 270px !important;
// }
/deep/.micro-dormitory-cascader-menu-item-content,
/deep/.micro-dormitory-cascader-menu-item,
/deep/.micro-dormitory-cascader-menu-item-expand {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  width: 270px !important;
}
/deep/ .micro-dormitory-tabs-dropdown {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  color: #333333;
  font-size: 14px;
  font-variant: tabular-nums;
  line-height: 1.5715;
  list-style: none;
  font-feature-settings: 'tnum';
  position: absolute !important;
  top: -9999px;
  left: -9999px;
  z-index: 1050;
  display: block;
}

/deep/ .micro-dormitory-tabs-dropdown-menu {
  max-height: 200px;
  margin: 0;
  padding: 4px 0;
  overflow-x: hidden;
  overflow-y: auto;
  text-align: left;
  list-style-type: none;
  background-color: #fff;
  background-clip: padding-box;
  border-radius: 5px;
  outline: none;
  box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
}
/deep/.micro-dormitory-tabs-dropdown-menu-item {
  display: flex;
  align-items: center;
  min-width: 120px;
  margin: 0;
  padding: 5px 12px;
  overflow: hidden;
  color: #000000d9;
  font-weight: 400;
  font-size: 14px;
  line-height: 22px;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
  transition: all 0.3s;
}
/deep/.micro-dormitory-table-content {
  min-height: 55vh;
}
:deep(.micro-dormitory-form-item-label) {
  max-width: 90px;
}
</style>
